package com.zxshhy.consumer;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.zxshhy.config.RabbitMqConfig;
import com.zxshhy.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

@Slf4j
@Component
public class StorageConsumer {

    @Resource
    private StorageService storageService;

    /**
     * 库存扣减队列消息
     * @param orderMessage
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitListener(queues = RabbitMqConfig.ZXSHHY_STORAGE_QUEUE)
    public void receiveStorageDeductQueueMsg(String orderMessage, Channel channel, Message message) throws IOException {
        log.info("接收到库存扣减队列消息：{}", orderMessage);
        try {
            JSONObject jsonObject = JSONObject.parseObject(orderMessage);
            String commodityCode = jsonObject.getString("commodityCode");
            Integer count = jsonObject.getInteger("count");
            storageService.deduct(commodityCode, count);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.info("库存【{}】扣减成功：{}个库存",commodityCode,count);
        } catch (IOException e) {
            log.error("库存扣减异常：", e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
        }
    }
}
